<!--时段号源，时间出错数据再编辑列表-->
<template>
  <div>
    <el-dialog
      :visible.sync="appoSelectedVisible"
      :destroy-on-close="true"
      style="top:-100px !important;"
      width="808px"
      class="ky-dialog">
      <template slot="title">
        <div class="flex flex-row align-center">
          <span class="el-dialog__title">编辑当日号源</span>
          <span class="mar-l-20" v-if="tableData.length>0">
            当前日期：{{dateFormatter('','',tableData[0].appointmentDate)}} {{tableData[0].week}}
          </span>
        </div>
      </template>
      <div class="appoError-wrap" style="margin-top:-10px;">
        <el-table
          :data="tableData"
          class="ky-table ky-table-sm"
          border
          v-loading="loading"
          style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column prop="beginTime" label="时段时间" width="170">
            <template slot-scope="scope">
              <div>
                {{scope.row.beginTime}}-{{scope.row.endTime}} （{{scope.row.checkClass}}）
              </div>
            </template>
          </el-table-column>
          <el-table-column label="总号源数" width="87" prop="totalNum">
          </el-table-column>
          <el-table-column prop="checkNum" label="号源数" width="100">
            <template slot-scope="scope">
              <div>
                <el-input v-model="scope.row.checkNum" style="width: 80px" @keyup.native="validNumber('checkNum', scope.row)"></el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="已预约" width="87" prop="callNum">
          </el-table-column>
          <el-table-column prop="reserveNum" width="100" :render-header="renderHeaderContainNumber">
            <template slot-scope="scope">
              <div>
                <el-input v-model="scope.row.reserveNum" style="width: 80px" @keyup.native="validNumber('reserveNum', scope.row)"></el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="addNum" label="追加" width="100">
            <template slot-scope="scope">
              <div>
                <el-input v-model="scope.row.addNum" style="width: 80px" @keyup.native="validNumber('addNum', scope.row)"></el-input>
              </div>
            </template>
          </el-table-column>
          <!--
          <el-table-column width="100" :render-header="renderHeaderInitNumber" style="display: none">
            <template slot-scope="scope">
              <span v-if="scope.row.partInit > 0" style="padding-left: 16px">{{scope.row.initialNum}}</span>
              <div v-else>
                <el-input v-model="scope.row.initialNum" style="width: 80px" @keyup.native="validNumber('initialNum', scope.row)"></el-input>
              </div>
            </template>
          </el-table-column>
          -->
          <!-- <el-table-column prop="checkNum" label="总号源数" width="100">
            <template slot-scope="scope">
              <div>
                <el-input v-model="scope.row.totalNum" style="width: 80px""></el-input>
              </div>
            </template>
          </el-table-column> -->
          <el-table-column label="状态" width="132" v-if="from == 'tempView'">
            <template slot-scope="scope">
              <el-select size="mini" v-model="scope.row.status" placeholder="请选择">
                <el-option v-for="item in appointmentStatusOptions" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="132" v-else>
            <template slot-scope="scope">
              <el-select size="mini" v-model="scope.row.appointmentStatus" placeholder="请选择">
                <el-option v-for="item in appointmentStatusOptions" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="">
        <div style="display: flex;justify-content: space-between">
          <div>
            <div class="tips tips_error" v-if="expire">提示：存在今天及今天之前的预约号源，暂不可修改！</div>
            <div class="tips" v-else><span style="color: #f00;">当前数据存入时段设置模板。需{{errorType === 'template'?'保存提交':'保存、发布'}}后才算修改完成！</span></div>
          </div>
          <div>
            <el-button size="mini" @click="appoSelectedVisible = false">关闭</el-button>
            <el-button size="mini" v-if="tableData.length>0 && !expire" type="primary" @click="save">保存</el-button>
          </div>
        </div>
      </span>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable */
import {
  updateappointmentstatus, putupdatecontinuitynum
} from '@/api/api'
import { Options } from '@/utils/constant'
import { dateFormatter } from '@/utils/validate'
import { getContinuityNum, getArgsCalNum } from '@/utils/schedule'

export default {
  props: {
    errorType: {
      type: String,
      default: ''
    },
    from: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      timeLevelObj: {},
      initNumObj: {}, // 下一行 号源 要是发生了比他大的变化，才能修改
      isContinuityNum: false, // 提交的时候 0 不连续， 1连续
      appoSelectedVisible: false,
      loading: false,
      expire: false,
      insertFlag: false,
      tableData: [],
      dataList:[],
      editData: {
        endTime: '',
        beginTime: ''
      },
      // 设置时间选项参数
      stepTime: window.g.DEFAULTSTEPTIME || '00:30',
      startTime: '00:00',
      endTime: '24:00',
      dialogVisible: false,
      statusRow: null,
      statusIndex: null,
      appointmentStatusOptions: Options.appointmentStatusOptions
    }
  },
  computed: {
    appConfig() {
      return this.$store.state.settings.appConfig
    },
    ISUSE_DEFAULTSTEPTIME() {
      return (this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.ISUSE_DEFAULTSTEPTIME) || window.g.ISUSE_DEFAULTSTEPTIME || false
    },
    // stepTime() {
    //   return (this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.DEFAULTSTEPTIME) || window.g.DEFAULTSTEPTIME || '00:30',
    // },
    startTimePickerOption() {
      return {
        start: this.startTime,
        step: this.stepTime,
        end: this.endTime,
        maxTime: this.editData.endTime
      }
    },
    endTimePickerOption() {
      return {
        start: this.startTime,
        step: this.stepTime,
        end: this.endTime,
        minTime: this.editData.beginTime
      }
    }
  },
  watch: {
    appoSelectedVisible(val) {
      if (!val) {
        this.data = []
      }
    }
  },
  created() {
    let appConfig = this.$store.state.settings.appConfig
    if (this.ISUSE_DEFAULTSTEPTIME) {
      this.stepTime = (appConfig && appConfig.baseConfig && appConfig.baseConfig.DEFAULTSTEPTIME) || window.g.DEFAULTSTEPTIME || '00:30'
    }
    if (this.from == 'tempView') {
      this.appointmentStatusOptions = Options.tempAppStatusOptions
    }
  },
  mounted() {
    this.isContinuityNum = getContinuityNum()
  },
  // class="" effect="dark" content="预留号只允许前台登记用，临床预约或移动预约等不能使用会过滤掉！" placement="top-end">
  methods: {
    renderHeaderInitNumber(h, { column, $index }) {
      return h(
        'div',
        [
          h('span','初始号码 '),
          h('el-tooltip',{
            props: {
              class:'item',
              content: '起始号码如果比同班次前面的号源小，会自动计算衔接于前面的号源数！',
              placement: 'top-end'
            }
          }, [
            h('i', {
              class:'el-icon-warning'
            })
          ], )
        ],
      );
    },
    renderHeaderContainNumber(h, { column, $index }) {
      return h(
        'div',
        [
          h('span','预留 '),
          h('el-tooltip',{
            props: {
              class:'item',
              content: '预留号只允许前台登记用，临床预约或移动预约等不能使用会过滤掉！',
              placement: 'top-end'
            }
          }, [
            h('i', {
              class:'el-icon-warning'
            })
          ], )
        ],
      );
    },
    filterHandler(value, row, column) {
      return row['checkClass'] === value
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    show() {
      this.appoSelectedVisible = true
    },
    open(data) {
      console.log('data',data)
      let _data = JSON.parse(JSON.stringify(data))
      this.expire = false
      this.tableData = []
      _data.forEach((it) => {
        if (it.appointment) {
          it.appointment.forEach((pItem, index) => {
            let partInit = 0
            pItem.forEach((item, idx) => {
              // console.log('不同时段的号源', item)
              // item.totalNum
              item.expire = false
              item.fullDate = it.dateFull
              if (new Date(it.dateFull.replace(/-/g, '/')).getTime() < new Date().getTime()) {
                item.expire = true
              }
              // item.partInit = partInit++
              // this.tableData.push(item)

              if (item.appointmentStatus || item.hospitalCode) {
                item.partInit = partInit++
                this.tableData.push(item)
              }

              // item.appointmentDate = it.dateFull
              // item.week = it.week
              // item.checkClass = this.checkClassOptions[index]
            })
          })
        }
        this.timeLevelObj = {} // 做键值对
        this.tableData.forEach((it, index) => {
          this.timeLevelObj[it.beginTime] = index
          this.initNumObj[it.beginTime] = it.initialNum
        })
      })

      this.dataList = _data
      console.log('this.tableData', this.tableData)
      if (this.tableData.length > 0) {
        this.appoSelectedVisible = true
      } else {
        this.$message.warning('请新建一条号源信息再选择编辑')
        this.appoSelectedVisible = false
      }
    },
    isNumric(value) {
      if( !isNaN(parseFloat(value))) {
        return parseInt(value)
      } else {
        return 0
      }
    },
    // 数据仅可输入数字判断
    validNumber(keyVal, item) {
      // item[keyVal] = item[keyVal] ? item[keyVal].replace(/[^\d]/g, '') : item[keyVal]
      this.calcInit()
    },
    calcInit() {
      console.log('this.initNumObj', this.initNumObj)
      const isCn = getContinuityNum()
      let len = this.tableData.length;
      this.tableData.forEach((item, index) => {
        let prev = index - 1 < 0 ? {} : this.tableData[index-1]
        if (index == 0 || (item.partInit == 0 && !isCn)) {

        } else {
          let newInit = (this.isNumric(prev.initialNum)) + (this.isNumric(prev.addNum))
          + (this.isNumric(prev.reserveNum)) + (this.isNumric(prev.checkNum)) + (this.isNumric(prev.callNum))
          // 如果下一个初始号码 大于 当前号码才更新
          let defaultInit = this.initNumObj[this.tableData[index].beginTime] || 0
          if (defaultInit <= newInit ) {
            item.initialNum = newInit
          } else {
            item.initialNum = defaultInit
          }
        }
      })
    },
    // 添加到参数模板，弹框
    openAddTemp() {
      if (this.validForm()) {
        this.dialogVisibleTemp = true
      }
    },
    // 保存
    save(row, index) {
      let weeks = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
      let number = weeks.indexOf(this.dataList[0].week)
      let scheduledata = this.$parent.$refs.fullschedule.scheduledata
      let scheduleDayData = scheduledata[number].appointment;
      // isCn 如果是true代表连续
      const isCn = getContinuityNum()
      let lastInitialNum = 0
      console.log('待查看timeLevelObj', this.timeLevelObj)
      console.log('待查看tableData', this.tableData)
      // 重新排号
      scheduleDayData.forEach((noon) => {
        noon.forEach((item)=>{
          if (item.initialNum || item.initialNum === 0){
            let index = this.timeLevelObj[item.beginTime]
            // console.log('待查看index', index)
            let Data = this.tableData[index];
            // console.log('待查看Data', Data)
            let midNum = 0
            let tNum = getArgsCalNum(Data.checkNum, Data.reserveNum, Data.addNum, Data.callNum)
            if (tNum == 0) {
              tNum = 1
            }
            if (item.initialNum < lastInitialNum) {
              if (lastInitialNum === 0) {
                  // 第一个循环的时候把初始值设置为第一个的初始号码
                  lastInitialNum = Data.initialNum * 1
              }
              item.initialNum = lastInitialNum + ''
            } else {
              // continuation：true 进入这里
              midNum = item.initialNum - lastInitialNum
            }
            const curInitialNum = midNum + tNum
            lastInitialNum = lastInitialNum + curInitialNum
            // item.initialNum = midNum + tNum // Data.initialNum
            // item.initialNum = Data.initialNum
            console.log('item.initialNum', item.initialNum)
            item.addNum = Data.addNum
            item.checkNum = Data.checkNum
            item.reserveNum = Data.reserveNum
            if (this.from == 'tempView') {
              item.status = Data.status
            } else {
              item.appointmentStatus = Data.appointmentStatus
            }
            // item.appointmentStatus = Data.appointmentStatus
            item.totalNum = (this.isNumric(item.callNum)) + (this.isNumric(item.addNum))
              + (this.isNumric(item.reserveNum)) + (this.isNumric(item.checkNum))
          }
        })
      })
      this.$parent.$refs.fullschedule.batchUpdate(scheduleDayData, number)
      this.appoSelectedVisible = false
    },
    statusFlr(status) {
      switch (status) {
        case '正常预约':
          return 'status_success'
        case '节假日':
          return 'status_danger'
        case '暂停预约':
        case '设备故障':
          return 'status_warn'
        case '计划排班':
          return 'status_default'
        default:
          return 'status_grey'
      }
    },
    statusFlr2(status) {
      switch (status) {
        case '启用':
          return 'status_default'
        case '停用':
          return 'status_grey'
        default:
          return 'status_grey'
      }
    },
    flrDate(rowDate) {
      // return new Date(dateFormatter(rowDate, false)).getTime() < new Date().getTime()
      return false
    },
    dateFormatter(row, column, cellValue, index) {
      return cellValue ? dateFormatter(cellValue, false) : ''
    },
    // 判断是否位24点，如果24点，则转为 23：59
    getEndTime(time) {
      if (!time) return ''
      const t = time.split(':')
      return t[0] * 1 === 24 ? '23:59' : time
    },
    getEndTimeM(time) {
      return time === '23:59' ? '24:00' : time
    }
  }
}
</script>

<style lang="scss" scoped>
$appoSuccessColor: #0bd677;
$appoSuccessBgColor: rgba(11, 214, 119, 0.08);
$appoSuccessBrColor: rgba(11, 214, 112, 0.4);
$appoDefaultColor: #1890FF;
$appoDefaultBgColor: rgba(26, 144, 255, 0.08);
$appoDefaultBrColor: rgba(24, 143, 255, 0.4);
$appoDangerColor: #E37470;
$appoDangerBgColor: rgba(227, 116, 112, 0.08);
$appoDangerBrColor: rgba(235, 79, 79, 0.4);
$appoWarnColor: #FF8618;
$appoWarnBgColor: rgba(255, 136, 24, 0.08);
$appoWarnBrColor: rgba(255, 136, 24, 0.4);
$appoGreyColor: #919398;
$appoGreyBgColor: rgba(145, 147, 152, 0.08);
$appoGreyBrColor: rgba(145, 147, 152, 0.4);
.status_tag{
  display: inline-block;
  padding: 2px 6px;
  border-radius: 3px;
  border: solid 1px $appoDefaultBrColor;
  background-color: $appoDefaultBgColor;
  font-size: 12px;
  color: $appoDefaultColor;
}
.status_default{
  border-color: $appoDefaultBrColor;
  background-color: $appoDefaultBgColor;
  color: $appoDefaultColor;
}
.status_success{
  border-color: $appoSuccessBrColor;
  background-color: $appoSuccessBgColor;
  color: $appoSuccessColor;
}
.status_danger{
  border-color: $appoDangerBrColor;
  background-color: $appoDangerBgColor;
  color: $appoDangerColor;
}
.status_warn{
  border-color: $appoWarnBrColor;
  background-color: $appoWarnBgColor;
  color: $appoWarnColor;
}
.status_grey{
  border-color: $appoGreyBrColor;
  background-color: $appoGreyBgColor;
  color: $appoGreyColor;
}
.appoError-wrap{
  padding: 15px 15px 0;
  max-height: calc(100vh - 130px);
  overflow-y: auto;
  overflow-x: hidden;
  .tips{
    margin-top: 20px;
    color: #333;
  }
  .tips_error{
    color: #f00;
  }
}
.date_expire{
  color: #f00;
}
.nsc-wrap{
  height: 100%;
  display: flex;
  flex-direction: column;
  // min-width: 600px;
  padding: 0 0 0 20px;
  /deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner{
    width: 120px;
  }
  /deep/ .el-form-item__label{
    font-weight: 500;
  }
  .nsc-m{
    padding:0px 0 54px;
    flex: 1;
    position: relative;
    .nsc-m-tit{
      font-size: 14px;
      font-weight: bold;
      padding: 4px 0;
    }
  }
  .nsc-footer{
    position: absolute;
    bottom: 0;
    left: 0;
    z-index: 2;
    width: 100%;
    text-align: right;
    padding: 10px 20px;
    border-top: solid 1px #DCDFE6;
    background-color: #fff;
  }
}
.edit-number-box /deep/ .el-dialog__body{
  padding: 10px 0;
}
/deep/ .el-table__column-filter-trigger i {
  color: #fff;
  font-size: 12px;
  -webkit-transform: scale(.75);
  transform: scale(.75);
  margin-left: 5px;
  font-weight: 800;
}
/deep/ .el-table th>.cell.highlight {
  color: #fff;
}
/deep/ .el-input__inner{
  height: 30px;
  line-height: 30px;
}
/deep/ .el-table .el-input__icon {
  line-height: 30px;
}
</style>
